/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.ittrick.drive.trick.custom;

import com.appspot.ittrick.drive.trick.controller.MainController;
import com.google.api.services.drive.model.File;
import java.util.List;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

/**
 *
 * @author takahara
 */
public class FolderTreeItem extends TreeItem<File> implements EventHandler<TreeItem.TreeModificationEvent<File>> {
    
    private final File file;

    public FolderTreeItem(File _file) {
        this.file = _file;
        this.setValue(file);
        
        this.addEventHandler(TreeItem.<File>branchExpandedEvent(), this);
        
    }
    
    @Override
    public boolean isLeaf() {
        return false;
    }
    
    /**
     * ファイルの取得
     * @return 
     */
    public File getFile() {
        return this.file;
    }

    /**
     * OPENイベント
     * @param e 
     */
    @Override
    public void handle(TreeModificationEvent<File> e) {

        final FolderTreeItem folderTreeItem = (FolderTreeItem) e.getSource();

        // 子がない要素だけが対象
        if (folderTreeItem.getChildren().isEmpty()) {

            MainController.getInstance().laodFolderListTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent t) {

                    List<FolderTreeItem> folderList = (List<FolderTreeItem>) t.getSource().getValue();
                    folderTreeItem.getChildren().setAll(folderList);

                    MainController.getInstance().folderTreeView.getSelectionModel().select(folderTreeItem);
                }
            });

            MainController.getInstance().laodFolderListTask.run(folderTreeItem.getFile().getId());
        }
    }

}
